
let EventEmitter = require('eventemitter3');


const templateDiv = `
    <span id="name"></span>
    <select id="select">
    </select>
`;

class Spinner{
    constructor(selectedIdx = 0,lstText,name='') {

        this._selectedIdx = -1;

        this.element = globalThis.document.createElement('div');
        this.element.innerHTML = templateDiv;

        this.nameEl = this.element.querySelector('#name');
        this.nameEl.innerText = name;

        // init ui
        this.selectEl = this.element.querySelector('#select');
        lstText.forEach((value,idx)=>{
            let optionEl = globalThis.document.createElement('option');
            optionEl.innerText = value;
            this.selectEl.appendChild(optionEl);
        });

        this.selectEl.addEventListener('change',this.onUIChanged.bind(this),false);

        // init event
        this.ee = new EventEmitter();
        this.ee.on('select',this.onDataSelected,this);

        this.setSelected(selectedIdx);
    }

    // data -> ui
    onDataSelected(){
        this.selectEl.selectedIndex = this._selectedIdx;
    }

    // ui->data
    onUIChanged(){
        this.setSelected(this.selectEl.selectedIndex);
        console.log(`selectedIdx:${this._selectedIdx}, type:${typeof this._selectedIdx}`);
    }

    setSelected(idx){
        this._selectedIdx = idx;
        this.ee.emit('select',this._selectedIdx);
    }

    getSelectedIndex(){
        return this._selectedIdx;
    }
}

module.exports = Spinner;
